// 源插件
import React, { Fragment, PureComponent } from 'react';
import {
  DateDiff,
  DateStamp,
  FormatnumberZero,
  Mover,
  NumberDivide,
  DateString,
} from '@/function.js';
// 视图插件
import { Button, Card, Divider, Form, message, Modal, notification } from 'antd';
// 外部组件
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTablePro from '@/components/UpgradeStandardTable/StandardTablePro';
import { connect } from 'dva';
import ReactKline from 'react-kline-pro';
import $ from 'jquery';
import UpdateModal from './UpdateModal';
import AddModal from './AddModal';
import KlineEchartsForeign from '../../../components/KlineEcharts/KlineEchartsForeign';
import UpdatePositionModal from './UpdatePositionModal';
import AddPositionModal from './AddPositionModal';
// css OR less预编译器

// 图片

/**
 *  Describe:数据连接
 */

@connect(({ foreign, loading }) => ({
  foreign,
  loading: loading.models.foreignRule,
}))
@Form.create()
class ForeignExchange extends PureComponent {
  componentWillMount() {}

  /**
   *  Describe:当前状态
   */

  state = {
    listLoading: false, // 加载状态
    dataSourceForeign: {
      data: [],
      total: [],
      code: 0,
    },
    dataSourceexpire: {
      data: [],
      total: [],
      code: 0,
    },
    addVisible: false,
    updateVisible: false,
    dataSourceForeignPosition: {
      data: [],
      total: [],
      code: 0,
    },
    addPositionVisible: false,
    updatePositionVisible: false,
    row: {},
    rowP: {},
    targetPrice: 0, // 目标价
    Visible: false,
    ExpireVisible: false,
    currency: '',
  };

  dataSourceChange() {
    const { dispatch } = this.props;
    const that = this;
    dispatch({
      type: 'foreign/GetTrack',
      payload: {},
      callback: res => {
        that.setState({
          dataSourceForeign: {
            title: '外汇交易',
            unfixed: true,
            code: 1,
            data: res.list,
            total: [],
            columns: [
              {
                title: '币种',
                dataIndex: 'currency',
                type: 'string',
                width: 80,
                sorter: true,
                search: true,
                render: (value, row, index) => {
                  return (
                    <div
                      onClick={this.klineModalOpen.bind(this, value)}
                      style={{ cursor: 'pointer' }}
                    >
                      {value}
                    </div>
                  );
                },
              },
              {
                title: '名称',
                dataIndex: 'currencyName',
                type: 'string',
                width: 90,
                sorter: true,
                search: true,
                // render: (value, row, index) => {
                //   return <div
                //     onClick={this.klineModalOpen.bind(this, value, row.targetPrice)}
                // style={{cursor: 'pointer'}}
                // >
                //   {value}
                // </div>
                // }
              },
              {
                title: '兑换率',
                width: 80,
                dataIndex: 'exchangeRate',
                type: 'number',
                sorter: true,
              },
              {
                title: '执行价（下）',
                width: 90,
                dataIndex: 'strikePriceDown',
                type: 'number',
                sorter: true,
              },
              {
                title: '执行价（上）',
                width: 90,
                dataIndex: 'strikePriceUp',
                type: 'number',
                sorter: true,
              },
              {
                title: '类型',
                dataIndex: 'type',
                type: 'number',
                width: 60,
                filters: [
                  {
                    text: 'SP',
                    value: '1',
                  },
                  {
                    text: 'SC',
                    value: '2',
                  },
                  {
                    text: 'BP',
                    value: '3',
                  },
                  {
                    text: 'BC',
                    value: '4',
                  },
                ],
                render: (value, row, index) => {
                  if (value === 1) {
                    return 'SP';
                  }
                  if (value === 2) {
                    return 'SC';
                  }
                  if (value === 3) {
                    return 'BP';
                  }
                  if (value === 4) {
                    return 'BC';
                  }
                  return value;
                },
              },
              {
                title: '交易日',
                width: 100,
                dataIndex: 'tradingDay',
                type: 'date',
                sorter: true,
                render: (value, row, index) => {
                  return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
                },
              },
              {
                title: '到期日',
                width: 100,
                dataIndex: 'expiryDate',
                type: 'date',
                sorter: true,
                render: (value, row, index) => {
                  return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
                },
              },
              {
                title: '距离PUT',
                width: 80,
                dataIndex: 'toPut',
                type: 'number',
                sorter: true,
                render: (value, row, index) => {
                  return value === null ? null : (
                    <span>{NumberDivide(mathService.mul(value, 100), 2, '%')}</span>
                  );
                },
              },
              {
                title: '距离CALL',
                width: 80,
                dataIndex: 'toCall',
                type: 'number',
                sorter: true,
                render: (value, row, index) => {
                  return value === null ? null : (
                    <span>{NumberDivide(mathService.mul(value, 100), 2, '%')}</span>
                  );
                },
              },
              {
                title: '距到期日',
                width: 80,
                dataIndex: 'toExpiryDate',
                type: 'number',
                sorter: true,
              },
              {
                title: '权利金',
                width: 80,
                dataIndex: 'premium',
                type: 'number',
                sorter: true,
              },
              {
                title: '备注',
                width: 100,
                dataIndex: 'mark',
                type: 'string',
              },
              {
                title: '市值（USD）',
                width: 80,
                dataIndex: 'marketValueUsd',
                type: 'number',
                sorter: true,
              },
              {
                title: '银行',
                width: 80,
                dataIndex: 'bank',
                type: 'number',
                // search: true,
                filters: [
                  {
                    text: '瑞银',
                    value: '1',
                  },
                  {
                    text: '中银',
                    value: '2',
                  },
                  {
                    text: '花旗',
                    value: '3',
                  },
                ],
                render: (value, row, index) => {
                  if (value === 1) {
                    return '瑞银';
                  }
                  if (value === 2) {
                    return '中银';
                  }
                  if (value === 3) {
                    return '花旗';
                  }
                  return value;
                },
              },
              {
                title: '有无确认',
                width: 80,
                dataIndex: 'confirm',
                type: 'string',
                render: (value, row, index) => {
                  if (value) {
                    return '是';
                  }
                  return '否';
                },
              },
              {
                title: '当时现价',
                width: 80,
                dataIndex: 'costPrice',
                type: 'number',
                sorter: true,
              },
              {
                title: '最新价',
                width: 80,
                dataIndex: 'latestPrice',
                type: 'number',
                sorter: true,
              },
              {
                title: '计算结果1',
                width: 100,
                dataIndex: 'calculateRet1',
                type: 'number',
                sorter: true,
                render: (value, row, index) => {
                  return value === null ? null : (
                    <span>{NumberDivide(mathService.mul(value, 100), 2, '%')}</span>
                  );
                },
              },
              {
                title: '计算结果2',
                width: 100,
                dataIndex: 'calculateRet2',
                type: 'number',
                sorter: true,
                render: (value, row, index) => {
                  return value === null ? null : (
                    <span>{NumberDivide(mathService.mul(value, 100), 2, '%')}</span>
                  );
                },
              },
              {
                title: '操作',
                fixed: 'right',
                render: (text, record) => (
                  <Fragment>
                    <a onClick={() => this.openUpdateVisible(record)}>修改</a>
                    <Divider type="vertical" />
                    <a onClick={() => this.deleteThis(record)}>删除</a>
                  </Fragment>
                ),
              },
            ],
          },
        });
      },
    });
    dispatch({
      type: 'foreign/GetExchangePosition',
      payload: {},
      callback: res => {
        that.setState({
          dataSourceForeignPosition: {
            title: '外汇现货持仓',
            unfixed: true,
            code: 1,
            data: res.list,
            total: [],
            columns: [
              {
                title: '币种',
                dataIndex: 'currency',
                type: 'string',
                width: 80,
                sorter: true,
                search: true,
              },
              {
                title: '银行',
                dataIndex: 'bank',
                type: 'number',
                width: 60,
                filters: [
                  {
                    text: '瑞银',
                    value: 1,
                  },
                  {
                    text: '中银',
                    value: 2,
                  },
                  {
                    text: '花旗',
                    value: 3,
                  },
                ],
                render: (value, row, index) => {
                  if (value === 1) {
                    return '瑞银';
                  }
                  if (value === 2) {
                    return '中银';
                  }
                  if (value === 3) {
                    return '花旗';
                  }
                  return value;
                },
              },
          // {
          //   title: '平仓日期',
          //   width: 100,
          //   dataIndex: 'closePositionDate',
          //   type: 'date',
          //   sorter: true,
          //   render: (value, row, index) => {
          //     return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
          //   },
          // },
          // {
          //   title: '平仓价格',
          //   width: 80,
          //   dataIndex: 'closePositionPrice',
          //   type: 'number',
          //   sorter: true,
          // },
          {
            title: '金额USD',
            width: 80,
            dataIndex: 'coin',
            type: 'number',
            sorter: true,
          },
          {
            title: '现价',
            width: 80,
            dataIndex: 'latestPrice',
            type: 'number',
            sorter: true,
          },
          {
            title: '盈亏USD',
            width: 80,
            dataIndex: 'profit',
            type: 'number',
            sorter: true,
          },
          {
            title: '接货日期',
            width: 100,
            dataIndex: 'receiptDate',
            type: 'date',
            sorter: true,
            render: (value, row, index) => {
              return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
            },
          },
          {
            title: '接货价',
            width: 80,
            dataIndex: 'receiptPrice',
            type: 'number',
            sorter: true,
          },
              {
                title: '操作',
                render: (text, record) => (
                  <Fragment>
                    <a onClick={() => this.openUpdatePositionVisible(record)}>修改</a>
                    <Divider type="vertical" />
                    <a onClick={() => this.deleteThisPosition(record)}>删除</a>
                  </Fragment>
                ),
              },
            ],
          },
        });
      },
    });
  }

  dataSourceChangeExpire() {}

  openAddVisible() {
    this.setState({
      addVisible: true,
    });
  }

  closeAddVisbile() {
    const that = this;
    this.setState(
      {
        addVisible: false,
      },
      () => {
        that.dataSourceChange();
      }
    );
  }

  openUpdateVisible(row) {
    this.setState({
      row,
      updateVisible: true,
    });
  }
  closeUpdateVisbile() {
    const that = this;
    this.setState(
      {
        updateVisible: false,
      },
      () => {
        that.dataSourceChange();
      }
    );
  }
  deleteThis(row) {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'foreign/DelExchange',
      payload: row.id,
      callback: res => {
        that.dataSourceChange();
      },
    });
  }

  openAddPositionVisible() {
    this.setState({
      addPositionVisible: true,
    });
  }
  closeAddPositionVisbile() {
    const that = this;
    this.setState(
      {
        addPositionVisible: false,
      },
      () => {
        that.dataSourceChange();
      }
    );
  }
  openUpdatePositionVisible(rowP) {
    this.setState({
      rowP,
      updatePositionVisible: true,
    });
  }
  closeUpdatePositionVisbile() {
    const that = this;
    this.setState(
      {
        updatePositionVisible: false,
      },
      () => {
        that.dataSourceChange();
      }
    );
  }
  deleteThisPosition(row) {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'foreign/DelExchangePosition',
      payload: row.id,
      callback: res => {
        that.dataSourceChange();
      },
    });
  }



  rowSetKey(record, index) {
    if (record.alarmFlag === 1) {
      return true;
    }
  }

  klineModalOpen(value) {
    const that = this;
    that.setState({ Visible: true, currency: value });
    /* that.setState({  }, () => {
       $.ajax({
         type: 'GET',
         url: 'http://fss.91stock.net/fss/Kline/GetStockInfo?code=' + value,
         contentType: 'application/x-www-form-urlencoded;charset=utf-8',
         dataType: 'json',
         async: false,
         success: function(data) {
           if (data.myCode !== null) {
             that.setState({ Visible: true, targetPrice:targetPrice, symbol: that.state.symbol===''?data.myCode:(data.myCode+'  '+Math.random())});
           } else {
             message.error('暂无该股票信息');
           }
         },
         error: function(e) {
           console.log(e);
         },
       });
     }); */
  }

  klineModalClose() {
    this.setState({ Visible: false });
  }

  openExpireVisible() {
    this.setState({ ExpireVisible: true }, () => {
      const { dispatch } = this.props;
      const that = this;
      dispatch({
        type: 'foreign/History',
        payload: {},
        callback: res => {
          that.setState({
            dataSourceexpire: {
              title: '到期列表',
              unfixed: true,
              code: 1,
              data: res.list,
              total: [],
              columns: [
                {
                  title: '币种',
                  dataIndex: 'currency',
                  type: 'string',
                  width: 80,
                  sorter: true,
                  search: true,
                  render: (value, row, index) => {
                    return (
                      <div
                        onClick={this.klineModalOpen.bind(this, value)}
                        style={{ cursor: 'pointer' }}
                      >
                        {value}
                      </div>
                    );
                  },
                },
                {
                  title: '名称',
                  dataIndex: 'currencyName',
                  type: 'string',
                  width: 90,
                  sorter: true,
                  search: true,
                  // render: (value, row, index) => {
                  //   return <div
                  //     onClick={this.klineModalOpen.bind(this, value, row.targetPrice)}
                  // style={{cursor: 'pointer'}}
                  // >
                  //   {value}
                  // </div>
                  // }
                },
                {
                  title: '兑换率',
                  width: 80,
                  dataIndex: 'exchangeRate',
                  type: 'number',
                  sorter: true,
                },
                {
                  title: '执行价（下）',
                  width: 90,
                  dataIndex: 'strikePriceDown',
                  type: 'number',
                  sorter: true,
                },
                {
                  title: '执行价（上）',
                  width: 90,
                  dataIndex: 'strikePriceUp',
                  type: 'number',
                  sorter: true,
                },
                {
                  title: '类型',
                  dataIndex: 'type',
                  type: 'number',
                  width: 60,
                  filters: [
                    {
                      text: 'SP',
                      value: '1',
                    },
                    {
                      text: 'SC',
                      value: '2',
                    },
                    {
                      text: 'BP',
                      value: '3',
                    },
                    {
                      text: 'BC',
                      value: '4',
                    },
                  ],
                  render: (value, row, index) => {
                    if (value === 1) {
                      return 'SP';
                    }
                    if (value === 2) {
                      return 'SC';
                    }
                    if (value === 3) {
                      return 'BP';
                    }
                    if (value === 4) {
                      return 'BC';
                    }
                    return value;
                  },
                },
                {
                  title: '交易日',
                  width: 100,
                  dataIndex: 'tradingDay',
                  type: 'date',
                  sorter: true,
                  render: (value, row, index) => {
                    return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
                  },
                },
                {
                  title: '到期日',
                  width: 100,
                  dataIndex: 'expiryDate',
                  type: 'date',
                  sorter: true,
                  render: (value, row, index) => {
                    return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
                  },
                },
                {
                  title: '距离PUT',
                  width: 80,
                  dataIndex: 'toPut',
                  type: 'number',
                  sorter: true,
                  render: (value, row, index) => {
                    return value === null ? null : (
                      <span>{NumberDivide(mathService.mul(value, 100), 2, '%')}</span>
                    );
                  },
                },
                {
                  title: '距离CALL',
                  width: 80,
                  dataIndex: 'toCall',
                  type: 'number',
                  sorter: true,
                  render: (value, row, index) => {
                    return value === null ? null : (
                      <span>{NumberDivide(mathService.mul(value, 100), 2, '%')}</span>
                    );
                  },
                },
                {
                  title: '距到期日',
                  width: 80,
                  dataIndex: 'toExpiryDate',
                  type: 'number',
                  sorter: true,
                },
                {
                  title: '权利金',
                  width: 80,
                  dataIndex: 'premium',
                  type: 'number',
                  sorter: true,
                },
                {
                  title: '备注',
                  width: 100,
                  dataIndex: 'mark',
                  type: 'string',
                },
                {
                  title: '市值（USD）',
                  width: 80,
                  dataIndex: 'marketValueUsd',
                  type: 'number',
                  sorter: true,
                },
                {
                  title: '银行',
                  width: 80,
                  dataIndex: 'bank',
                  type: 'number',
                  // search: true,
                  filters: [
                    {
                      text: '瑞银',
                      value: '1',
                    },
                    {
                      text: '中银',
                      value: '2',
                    },
                    {
                      text: '花旗',
                      value: '3',
                    },
                  ],
                  render: (value, row, index) => {
                    if (value === 1) {
                      return '瑞银';
                    }
                    if (value === 2) {
                      return '中银';
                    }
                    if (value === 3) {
                      return '花旗';
                    }
                    return value;
                  },
                },
                {
                  title: '有无确认',
                  width: 80,
                  dataIndex: 'confirm',
                  type: 'string',
                  render: (value, row, index) => {
                    if (value) {
                      return '是';
                    }
                    return '否';
                  },
                },
                {
                  title: '当时现价',
                  width: 80,
                  dataIndex: 'costPrice',
                  type: 'number',
                  sorter: true,
                },
                {
                  title: '最新价',
                  width: 80,
                  dataIndex: 'latestPrice',
                  type: 'number',
                  sorter: true,
                },
                {
                  title: '计算结果1',
                  width: 100,
                  dataIndex: 'calculateRet1',
                  type: 'number',
                  sorter: true,
                  render: (value, row, index) => {
                    return value === null ? null : (
                      <span>{NumberDivide(mathService.mul(value, 100), 2, '%')}</span>
                    );
                  },
                },
                {
                  title: '计算结果2',
                  width: 100,
                  dataIndex: 'calculateRet2',
                  type: 'number',
                  sorter: true,
                  render: (value, row, index) => {
                    return value === null ? null : (
                      <span>{NumberDivide(mathService.mul(value, 100), 2, '%')}</span>
                    );
                  },
                },
              ],
            },
          });
        },
      });
    });
  }

  closeExpireVisible() {
    this.setState({ ExpireVisible: false });
  }

  render() {
    const {
      addVisible,
      updateVisible,
      addPositionVisible,
      updatePositionVisible,
      row,
      rowP,
      dataSourceForeign,
      Visible,
      ExpireVisible,
      currency,
      dataSourceexpire,
      dataSourceForeignPosition,
    } = this.state;
    return (
      <PageHeaderWrapper>
        <Card>
          <Button onClick={this.openAddVisible.bind(this)}>添加外汇追踪</Button>
          <Button onClick={this.openExpireVisible.bind(this)} style={{ marginLeft: 25 }}>
            到期列表
          </Button>
          <Button onClick={this.openAddPositionVisible.bind(this)} style={{ marginLeft: 25 }}>添加外汇现货持仓</Button>
          <br />
          <br />
          <StandardTablePro dataSource={dataSourceForeign} rowSetKey={this.rowSetKey.bind(this)} />
          <AddModal closeVisbile={this.closeAddVisbile.bind(this)} visible={addVisible} />
          <UpdateModal
            closeVisbile={this.closeUpdateVisbile.bind(this)}
            visible={updateVisible}
            row={row}
          />
          <br />
          <br />
          <StandardTablePro dataSource={dataSourceForeignPosition} rowSetKey={this.rowSetKey.bind(this)} />
          <AddPositionModal closeVisbile={this.closeAddPositionVisbile.bind(this)} visible={addPositionVisible} />
          <UpdatePositionModal
            closeVisbile={this.closeUpdatePositionVisbile.bind(this)}
            visible={updatePositionVisible}
            row={rowP}
          />

          <Modal
            width="90%"
            title={currency}
            footer=""
            visible={Visible}
            centered
            onOk={this.klineModalClose.bind(this)}
            onCancel={this.klineModalClose.bind(this)}
            destroyOnClose
          >
            <KlineEchartsForeign symbol={currency} mainId="ForeignExchangeEcharts" />
          </Modal>

          <Modal
            width="90%"
            title="到期列表"
            footer=""
            visible={ExpireVisible}
            centered
            onOk={this.closeExpireVisible.bind(this)}
            onCancel={this.closeExpireVisible.bind(this)}
            destroyOnClose
          >
            <StandardTablePro dataSource={dataSourceexpire} rowSetKey={this.rowSetKey.bind(this)} />
          </Modal>
        </Card>
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    this.dataSourceChange();
    // window.halfHourRefresh =  window.setInterval(()=>{
    //     if((1000 > Date.parse(new Date())%300000) && (Date.parse(new Date())%300000 >= 0)){
    //       this.dataSourceChange();
    //       message.success(DateString(new Date())+' 更新外汇列表')
    //     }
    //   }
    // }, 1000);
  }

  componentWillUnmount() {}
}

export default ForeignExchange;
